<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require_once __DIR__.'/../../utils/checkTokenUtils.php';
require_once __DIR__ . '/../../model/UserModel.php';
require_once __DIR__ . '/../../utils/PasswordUtils.php';
use model\UserModel;

if ($_SERVER['REQUEST_METHOD']!=='POST'){
    http_response_code(405);
    $_SESSION['error_message'] = '错误：仅支持POST请求';
    header("Location: Users.php");
}

$id=isset($_POST['id'])? intval($_POST['id']):0;
$password_updated=isset($_POST['password_updated'])? intval($_POST['password_updated']):0;
$username=isset($_POST['username'])? trim($_POST['username']):'';
$password=isset($_POST['password'])? trim($_POST['password']):'';
$realName=isset($_POST['name'])? trim($_POST['name']):'';
$phone=isset($_POST['phone'])? trim($_POST['phone']):'';
$email=isset($_POST['email'])? trim($_POST['email']):'';
$role=isset($_POST['role'])? intval($_POST['role']):0;

$errors = [];

if (empty($username) || strlen($username) < 3 || strlen($username) > 10){
    $errors[] = '用户名需为3-10位字符';
}

// 密码验证
if ($password_updated==1){
    if (empty($password) || strlen($password) < 4 || strlen($password) > 16) {
        $errors[] = '密码需为4-16位字符';
    }
}

// 真实姓名验证
if (empty($realName)) {
    $errors[] = '真实姓名不能为空';
}

// 手机号验证
if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
    $errors[] = '手机号格式不正确';
}

//邮箱验证
if (!preg_match('/^[\w\-]+@[\w\-]+\.[a-z]{2,}$/i', $email)) {
    $errors[] = '邮箱格式不正确';
}

//权限验证
if (!in_array($role, [0, 1])) {
    $errors[] = '权限设置错误';
}

if (empty($errors)) {
    $userModel = new UserModel();
    $data = [
        'username' => $username,
        'name' => $realName,
        'phone' => $phone,
        'email' => $email,
        'role' => $role
    ];

    if ($password_updated==1){
        $data['password']=$password;
    }

    $result=$userModel->updateUser($id,$data,$password_updated);
    if ($result){
        $_SESSION['success_message'] = '用户更新成功';
    }else{
        $_SESSION['error_message'] = '用户更新失败';
    }
}else{
    $_SESSION['error_message'] = implode( $errors);
}

header('Location: Users.php');
exit;